import os, sys, shutil
import py_compile

cur_dir_fullpath = os.path.dirname(os.path.abspath(__file__))

#清空目录
def ClearDir(dir):
    print('ClearDir ' + dir + '...')
     
    for entry in os.scandir(dir):
        if entry.name.startswith('.'):
            continue
        if  entry.is_file():   
            os.remove(entry.path)    #删除文件
        else:                  
            shutil.rmtree(entry.path)    #删除目录
            
#编译当前文件夹下所有.py文件
def WalkerCompile():
    dstDir = os.path.join(cur_dir_fullpath, 'bin')
    if os.path.exists(dstDir):    #如果存在，清空
        ClearDir(dstDir)
    else:                        #如果不存在，创建
        os.mkdir(dstDir)
    #递归编译
    com_file(cur_dir_fullpath+"/src",cur_dir_fullpath+"/bin")
    print("编译成功")  

def com_file(srcPath,binPath):
    for filename in os.listdir(srcPath):
        if os.path.isdir(srcPath+"/"+filename):
            #建立对应文件夹
            if os.path.exists(binPath+"/"+filename) == False:
                os.mkdir(binPath+"/"+filename)
            com_file(srcPath+"/"+filename,binPath+"/"+filename)
        elif not filename.endswith('.py'):
            #复制文件
            if os.path.exists(binPath+"/"+filename) == False:
                shutil.copyfile(srcPath+"/"+filename,binPath+"/"+filename)
            continue
        srcFile = os.path.join(srcPath, filename)
        if os.path.isdir(srcPath+"/"+filename):
            continue
        dstFile = os.path.join(binPath+"/", filename + 'c')
        #编译文件
        py_compile.compile(srcFile, cfile=dstFile)
        print(srcFile + ' --> ' + dstFile)
        
if __name__ == "__main__":
    WalkerCompile()